// miniprogram/pages/admin/service/newService/newService.js
const MAX_IMAGE_SIZE = 1024 * 1024 * 1024;
const app = getApp();
const util = require("../../../utils/util");
const uploader = require("../../../utils/upload");
Page({
  removeImages: [],

  /**
   * 页面的初始数据
   */
  data: {
    // 缺省套系
    isMoving: false,
    pr: {
      desc:'记录生活/自然光/日系文艺风格',
      category: '不分类',
      price: 1500,
      deposit: 500,
      hours: 2,
      clothes: 0,
      scene: 1,
      film: 50,
      album: 10,
      filmGive: true,
      albumGive: true,
      coupon: {
        price: 35,
        couponType: 0,
        amount: 10,
        bonus: 2,
        desc: '加片35元/张'
      },
      fixCoupon: {
        price: 50,
        couponType: 0,
        amount: 10,
        bonus: 2,
        desc: '加片50元/张'
      },
      startDate: '',
      // startTime: '09:00',
      endDate: '',
      // endTime: '23:59',
      isLimit: false,
      limit: 100,
      status:0,
      visit: 0,
      sales: 0,
      samples:[

      ],
      nodes: `<p><strong>拍摄时长：</strong>大约1小时。</p>
      <p><strong>妆面服装：</strong>本套系不带妆面，服装建议自带。</p>
      <p><strong>后期产品：</strong>8寸拉米，12寸水晶相册。</p>
      <p><strong>温馨提示：</strong></p>
      <ol><li>拍摄前尽量让小朋友休息好，避免生病，保持良好的情绪,为了宝贝能在拍摄有最佳状态，打疫苗三天内不预约拍摄。</li><li>拍摄时给小朋友带上喜爱的玩具，和爱吃的食物,有纪念意义的小物件等都可以带来作为拍摄道具。 </li><li>服装建议，不要出现大面积印花和卡通图案，这样会抢了孩子的光彩，干净素色或者色彩鲜艳的简单款式即可，这样能保证孩子的照片更有‘自己’的成长印记，切记不给孩子带开档的裤子哟。</li><li>爸爸妈妈可以跟孩子一起玩耍哦，不用要求宝宝看镜头，更多的还是在不受干扰的自然状态下进行拍摄。</li><li>拍摄前我们会跟您要几张宝贝照片，沟通家长喜欢的拍摄风格。如果家长们没有指定拍摄场景，我们就会根据宝贝的气质、肤色等，提前一天写好拍摄思路，搭配好专属宝贝们的服装、场景。</li><li>愿拍摄合作开心，留下一次美好的记忆。</li></ol>`

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.login(user => {
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      if (options._id) {
        wx.setNavigationBarTitle({
          title: '套系编辑',
        })
        this.loadItem(options, user);
      }
    });
  },
  // getNode(e) {
  //   console.log('页面获取到值', e.detail) 
  //   // let service = this.data.pr;
  //   this.setData({'pr.nodes': e.detail});
  // },

  isMoving(e) {
    console.log(e.detail)
    this.setData({
      isMoving: e.detail.isMoving
    })
  },
  isEditing(e) {
    console.log('isEditing',e.detail)
    this.setData({
      isEditing: e.detail.isEditing
    })
  },
  loadItem: function (options, user) {
    const that = this;
    wx.showNavigationBarLoading();
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'service',
        where: {
          _id: options._id,
          studioid: user.studioid
        }
      },
      success: res => {
        if (res.result.data && res.result.data.length > 0)
          that.setData({
            pr: res.result.data[0]
          })
        wx.hideNavigationBarLoading();
      }
    });
  },

  changeCategory: function (e) {
    const category = this.data.pr.category;
    const that = this;
    wx.navigateTo({
      url: `/pages/admin/category/category?category=${category}`,
      events: {
        'changeCategory': function (res) {
          that.setData({
            ['pr.category']: res.item
          });
        }
      }
    })
  },

  // removeImage: function(e){
  //   console.log(e);
  //   this.removeImages.push(e.detail.src);
  // },
  
  /**
   * 保存数据
   */
  submitData: function (service) {
    const that = this;
    wx.showLoading({
      title: '正在保存数据'
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        table: 'service',
        op: 'update',
        data: service
      },
      success: res => {
       
        wx.hideLoading();
        console.debug("Update result", res.result);
        let pages = getCurrentPages();
        if (res.result._id || res.result.stats.updated) {
          if (pages.length > 1) {
            pages[pages.length - 2].onLoad();
          }
          wx.navigateBack();
        }
      },
      fail: err => {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },

  apply: function (e) {


    let service = this.data.pr;
    for (var n in e.detail.value) {
      service[n] = e.detail.value[n]
    }
    
    if (!service._id) {
      if (app.globalData.user.studioid) {
        service.studioid = app.globalData.user.studioid;
      } else {
        wx.showModal({
          title: '提示',
          content: '您没有对应工作室，请创建或由主账号邀请加入',
          showCancel: false,
          success: r => {
            if (r.confirm) {
              wx.navigateTo({
                url: '../../studio/studio'
              })
            }
          }
        })
        return;
      }
      service.visit = 0;
      service.sales = 0;
    }

    service.updatetime = util.formatTime(new Date());
    service.nodes = this.selectComponent('#zEditor').data.nodes;
    service.samples = this.selectComponent('#dragger').data.items;

    this.submitData(service);

  },

  chooseImg: function(){
    const that = this;
    wx.navigateTo({
      url: '../../gallary/gallary',
      success: res => {
        res.eventChannel.on('setImages', items => {
          if (items.length >= 1)
            that.setData({
              ['pr.cover']: items[0]
            });
        });
        res.eventChannel.emit('setImages', {
          count: 1
        });
      }
    })
  },

  // chooseImg1: function(){
  //   let that = this;
  //   wx.chooseImage({
  //     sizeType: ['compressed'],
  //     count: 1,
  //     success: res => {
  //       res.tempFiles.map((tempFile, index) => {
  //         if (tempFile.size > MAX_IMAGE_SIZE){
  //           wx.showToast({
  //             title: '图片过大，请重新选择',
  //             icon: 'none'
  //           })
  //           return;
  //         }
  //         // TODO 如果文件较大，自动启用压缩
  //         wx.getImageInfo({
  //           src: tempFile.path,
  //           success: r => {
  //             let cover = {
  //               src: tempFile.path,
  //               size: tempFile.size,
  //               width: r.width / r.height,
  //               uploaded: false
  //             }
  //             if (that.data.pr.cover && that.data.pr.cover.uploaded){
  //               that.removeImages.push(that.data.pr.cover.src);
  //             }
  //             that.setData({['pr.cover']: cover});
  //           }
  //         })
  //       });
  //     },
  //   })
  // },

  insertImg(e) {
    console.log(e);
    const that = this;
    wx.navigateTo({
      url: '/pages/admin/gallary/gallary',
      success: res => {
        res.eventChannel.on('setImages', items => {
          for (let i = 0; i < items.length; i++) {
            let tempFile = items[i];
            e.detail.insertImage({
              src: tempFile,
              // data: {
              //   id: 'img'+i,
              //   role: 'img'+i
              // },
              width: '100%',
              success: function () {
                console.log('insert image success')
              }
            })
          }
        });
        res.eventChannel.emit('setImages', {
          count: 9
        });
      }
    })
  },

  switchChange: function (e) {
    if (e.target.id) {
      this.setData({
        [`pr.${e.target.id}`]: e.detail.value
      });
    } else {
      console.error("控件没有设置 id!")
    }
  },

  setCoupon: function (e) {
    const that = this;
    let fixCoupon = e.currentTarget.dataset.index == 'fixCoupon';
    let coupon = fixCoupon ? this.data.pr.fixCoupon : this.data.pr.coupon;
    if (!coupon) {
      coupon = this.data.pr.coupon;
    }
    wx.navigateTo({
      url: '../../chooseMorePolicy/chooseMorePolicy',
      events: {
        setCoupon: res => {
          console.log("result", res);
          if (fixCoupon) {
            that.setData({
              ['pr.fixCoupon']: res.coupon
            });
          } else {
            that.setData({
              ['pr.coupon']: res.coupon
            });
          }
        }
      },
      success: res => {
        res.eventChannel.emit('setCoupon', {
          coupon: coupon
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})